package com.wlwk.common.yidong;

import com.wlwk.common.exception.RRException;
import com.wlwk.common.exception.menu.RespCode;
import com.wlwk.common.http.PostXml;
import com.wlwk.common.util.DateUtils;
import com.wlwk.common.util.JsonUtils;
import com.wlwk.common.util.XMLUtil;
import com.wlwk.model.FlowInfoView;
import com.wlwk.model.plat.QueryRealTimeGPRS;
import com.wlwk.model.userInfo.PoolList;
import com.wlwk.model.userInfo.ProdList;
import com.wlwk.model.userInfo.UserPoolGprs;
import com.wlwk.model.userInfo.UserProdGprs;
import com.wlwk.model.userState.QueryUserState;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChangZhouUrl {

    private final static String APP_ID = "109000000404";

    private final static String ACCESS_TOKEN = "109000000404";

    private final static String ECCODE = "250241138250250000";

    private final static String Url = "http://221.178.251.182:80/internet_surfing";

    private final static String OPEN_QRYINTERNETGRPPOOLGPRS = "OPEN_QRYINTERNETGRPPOOLGPRS";

    private final static String OPEN_QRYINTERNETUSERGPRS = "OPEN_QRYINTERNETUSERGPRS";

    private final static String CC_QRYUSERINFO = "cc_qryuserinfo";


    /**
     * 接口请求报文头
     * @param url 请求地址
     * @return
     */
    public static StringBuilder baseInfoXml(String url){
        //获取当前时间
        String nowTime =  DateUtils.getNowTime(DateUtils.DATE_MONTH_TIME);
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"GBK\" ?>");
        sb.append("<operation_in>");
        sb.append("<process_code>"+url+"</process_code>");
        sb.append("<app_id>"+ APP_ID +"</app_id>");
        sb.append("<access_token>"+ ACCESS_TOKEN +"</access_token>");
        sb.append("<sign></sign>");
        sb.append("<verify_code></verify_code>");
        sb.append("<req_type></req_type>");
        sb.append("<terminal_id></terminal_id>");
        sb.append("<accept_seq></accept_seq>");
        sb.append("<req_time>" +nowTime+ "</req_time>");
        sb.append("<req_seq>0_9834345</req_seq>");

        return sb;
    }

    /**
     * 3.1 实时查询本月平台总流量使用情况
     * @return
     */
    public static QueryRealTimeGPRS openQryInternetGrpPoolGprs() {
        String nowMonth =  DateUtils.getNowTime(DateUtils.DATE_MONTH);
        StringBuilder sb = baseInfoXml(OPEN_QRYINTERNETGRPPOOLGPRS);
        sb.append("<content>");
        sb.append("<qrytype>0</qrytype>");
        sb.append("<eccode>"+ECCODE+"</eccode>");
        sb.append("<cycle>"+nowMonth+"</cycle>");
        sb.append("</content>");
        sb.append("</operation_in>");
        String stringXml = PostXml.postXml(Url,sb.toString());
        System.out.println("===========stringXml为============");
        System.out.println(stringXml);
        QueryRealTimeGPRS q2 = (QueryRealTimeGPRS) XMLUtil.convertXmlStrToObject(QueryRealTimeGPRS.class, stringXml);
        return q2;
    }

    /**
     *  3.3 物联网单卡本月实时流量查询接口
     * @param number
     * @return
     */
    public static String qryInternetUserGprs(String number,String ebid) {
        if(StringUtils.isEmpty(number) || StringUtils.isEmpty(ebid)){
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        Map<String, Object> map = new HashMap();
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (StringUtils.equals("0001000000083", ebid)) {
            UserPoolGprs userPoolGprs = queryPoolGprs(number);
            //判断是否成功
            Long emergencyStatus = userPoolGprs.getEmergency_status();
            String message = userPoolGprs.getResponse().getResp_desc();

            if (emergencyStatus.intValue() == 0) {
                String respDesc = userPoolGprs.getResponse().getResp_desc();
                if (StringUtils.equals(respDesc, "成功")) {
                    //判断是动态流量池应答报还是没有加入动态流量池应答报文
                    List<PoolList> poolList = userPoolGprs.getContent().getPoollist();
                    List<FlowInfoView> list = new ArrayList<>();
                    if (poolList == null || poolList.size() == 0) {
                        //非流量池
                        UserProdGprs userProdGprs = queryProdGprs(number);
                        List<ProdList> prodList = userProdGprs.getContent().getProdlist();
                        for (int i = 0; i < prodList.size(); i++) {
                            String prodinstid = prodList.get(i).getProdinfo().getProduct_code(); //套餐编码
                            String prodname = prodList.get(i).getProdinfo().getProduct_name(); //套餐名称
                            Long used = prodList.get(i).getProdinfo().getCumulate_value(); //通信已使用量（KB）
                            Long left = prodList.get(i).getProdinfo().getLeft_value(); //通信使用剩余量（KB）
                            Long total = used + left;//通信资源总量（KB）
                            FlowInfoView flow = new FlowInfoView();
                            flow.setApnname("CMIOT");
                            flow.setLeft(String.valueOf(left));
                            flow.setProdinstid(prodinstid);
                            flow.setProdname(prodname);
                            flow.setTotal(String.valueOf(total));
                            flow.setUsed(String.valueOf(used));
                            list.add(flow);
                        }
                    } else {
                        //流量池的卡
                        for (int i = 0; i < poolList.size(); i++) {
                            String prodinstid = poolList.get(i).getPoolinfo().getProduct_id(); //套餐编码
                            String prodname = poolList.get(i).getPoolinfo().getProduct_name(); //套餐名称
                            Long used = poolList.get(i).getPoolinfo().getPool_left_value(); //通信已使用量（KB）
                            Long left = poolList.get(i).getPoolinfo().getCumulate_value(); //通信使用剩余量（KB）
                            Long total = used + left;//通信资源总量（KB）
                            FlowInfoView flow = new FlowInfoView();
                            flow.setApnname("CMIOT");
                            flow.setLeft(String.valueOf(left));
                            flow.setProdinstid(prodinstid);
                            flow.setProdname(prodname);
                            flow.setTotal(String.valueOf(total));
                            flow.setUsed(String.valueOf(used));
                            list.add(flow);
                        }
                    }
                    Map<String, Object> info = new HashMap<>();
                    info.put("gprs", list);
                    mapList.add(info);
                    map.put("result", mapList);
                    String json = JsonUtils.toJson(map);
                    return json;
                } else {
                    throw new RRException(message);
                }
            } else {
                throw new RRException(message);
            }
        } else {
            //查询用户状态和基本信息
            QueryUserState queryUserState = qryUserInfo(number);
            String resCode = queryUserState.getResponse().getResp_code();
            String message = queryUserState.getResponse().getResp_desc();

            //成功
            if (StringUtils.equals("0000", resCode)) {
                String statusName = "";
                String status = queryUserState.getContent().getStatus();
                //卡的状态
                switch (status) {
                    case "1":
                        statusName = "正常";
                        break;
                    case "2":
                        statusName = "待激活";
                        break;
                    case "3":
                        statusName = "停机";
                        break;
                    case "4":
                        statusName = "销户";
                        break;
                    default:
                        statusName = "未知";
                        break;
                }
                Map<String, Object> info = new HashMap<>();
                info.put("STATUS", statusName);
                mapList.add(info);
                map.put("result", mapList);
                String json = JsonUtils.toJson(map);
                return json;
            }else{
                throw new RRException(message);
            }
        }
    }
    /**
     * 查询流量池流量信息
     * @param number
     * @return
     */
    public static UserPoolGprs queryPoolGprs(String number) {
        String nowMonth = DateUtils.getNowTime(DateUtils.DATE_MONTH);
        StringBuilder sb = baseInfoXml(OPEN_QRYINTERNETUSERGPRS);
        sb.append("<content>");
        sb.append("<service_number>" + number + "</service_number>");
        sb.append("<cycle>" + nowMonth + "</cycle>");
        sb.append("</content>");
        sb.append("</operation_in>");
        String stringXml = PostXml.postXml(Url, sb.toString());
        System.out.println("===========stringXml为============");
        System.out.println(stringXml);
        UserPoolGprs poolGprs = (UserPoolGprs) XMLUtil.convertXmlStrToObject(UserPoolGprs.class, stringXml);
        return poolGprs;
    }
    /**
     * 查询非流量池流量信息
     * @param number
     * @return
     */
    public static UserProdGprs queryProdGprs(String number) {
        String nowMonth =  DateUtils.getNowTime(DateUtils.DATE_MONTH);
        StringBuilder sb = baseInfoXml(OPEN_QRYINTERNETUSERGPRS);
        sb.append("<content>");
        sb.append("<service_number>"+number+"</service_number>");
        sb.append("<cycle>"+nowMonth+"</cycle>");
        sb.append("</content>");
        sb.append("</operation_in>");
        String stringXml = PostXml.postXml(Url,sb.toString());
        System.out.println("===========stringXml为============");
        System.out.println(stringXml);
        UserProdGprs q2 = (UserProdGprs) XMLUtil.convertXmlStrToObject(UserProdGprs.class, stringXml);
        return q2;
    }

    /**
     * 查询卡状态和基本信息
     * @param number
     * @return
     */
    public static QueryUserState qryUserInfo(String number) {
        StringBuilder sb = baseInfoXml(CC_QRYUSERINFO);
        sb.append("<content>");
        sb.append("<ddr_city>12</ddr_city>");
        sb.append("<msisdn>"+number+"</msisdn>");
        sb.append("</content>");
        sb.append("</operation_in>");
        String stringXml = PostXml.postXml(Url,sb.toString());
        System.out.println("===========stringXml为============");
        System.out.println(stringXml);
        QueryUserState q2 = (QueryUserState) XMLUtil.convertXmlStrToObject(QueryUserState.class, stringXml);
        return q2;
    }
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap();
        List<Map<String, Object>> mapList = new ArrayList<>();
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\" ?><operation_out><process_code>cc_qryuserinfo</process_code><sysfunc_id></sysfunc_id><response_time>20190311110524</response_time><request_type></request_type><request_seq>0_9834345</request_seq><request_source>102010</request_source><response><resp_result>0</resp_result><resp_code>14810001</resp_code><resp_desc>手机号码不存在或已销户。</resp_desc><resp_type>1</resp_type></response><content><ret_code>1</ret_code><ret_msg>手机号码不存在或已销户。</ret_msg><msisdn></msisdn><imsi></imsi><iccid></iccid><status>4</status><username></username><brand></brand><Effdate></Effdate><Expdate></Expdate></content><emergency_status>0</emergency_status></operation_out>";
        QueryUserState queryUserState = (QueryUserState) XMLUtil.convertXmlStrToObject(QueryUserState.class, xml);
        System.out.print(queryUserState);
        String resCode = queryUserState.getResponse().getResp_code();
        //成功
        if (!StringUtils.equals("0000", resCode)) {
            String statusName = "";
            String status = queryUserState.getContent().getStatus();
            //卡的状态
            switch (status) {
                case "1":
                    statusName = "正常";
                    break;
                case "2":
                    statusName = "待激活";
                    break;
                case "3":
                    statusName = "停机";
                    break;
                case "4":
                    statusName = "销户";
                    break;
                default:
                    statusName = "未知";
                    break;
            }
            Map<String, Object> info = new HashMap<>();
            info.put("STATUS", statusName);
            mapList.add(info);
            map.put("result", mapList);
            String json = JsonUtils.toJson(map);
        }else{
            throw new RRException(RespCode.NOT_INTER_ERROR);
        }
    }

}
